package org.mspring.mlog.web.module.admin;

import java.net.URL;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mspring.mlog.entity.Attachment;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.AttachmentService;
import org.mspring.mlog.utils.UploadUtils;
import org.mspring.mlog.web.query.AttachmentQueryCriterion;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.dao.support.Sort;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 附件管理
 * 
 * @author Gao Youbo
 * @since 2013年7月3日
 */
@Widget
@RequestMapping("/admin/attachment")
@SuppressWarnings({ "rawtypes" })
public class Admin_AttachmentWidget extends Admin_AbstractWidget {
    @Autowired
    private AttachmentService attachmentService;

    @RequestMapping("/list")
    public String list(@ModelAttribute Page<Attachment> attachmentPage, @ModelAttribute Attachment attachment, @RequestParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (attachmentPage == null) {
            attachmentPage = new Page<Attachment>();
        }
        if (attachmentPage.getSort() == null) {
            attachmentPage.setSort(new Sort("id", Sort.DESC));
        }
        // 默认查看已发布的文章
        if (attachment == null) {
            attachment = new Attachment();
        }
        attachmentPage = attachmentService.listPage(new AttachmentQueryCriterion(queryParams), attachmentPage);
        model.addAttribute("attachmentPage", attachmentPage);
        return "/admin/attachment/listAttachment";
    }

    @RequestMapping("/view")
    public String view(@RequestParam(required = false) Long id, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (id == null) {
            return prompt(model, "请选择要查看的附件");
        }
        Attachment attachment = attachmentService.get(id);
        if (attachment == null) {
            return prompt(model, "未找到相应的附件");
        }
        model.addAttribute("attachment", attachment);
        return "/admin/attachment/viewAttachment";
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam(required = false) Long id, @ModelAttribute Page<Attachment> attachmentPage, @ModelAttribute Attachment attachment, @RequestParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        attachmentService.deleteAttachment(id);
        return list(attachmentPage, attachment, queryParams, request, response, model);
    }

    /**
     * 下载远程图片
     * 
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/remote")
    @ResponseBody
    public ResponseEntity downloadRemoteImages(HttpServletRequest request, HttpServletResponse response, Model model) {
        String fid = RequestUtils.getRequestParameterAsString(request, "fid");
        String ftype = RequestUtils.getRequestParameterAsString(request, "ftype");
        String content = RequestUtils.getRequestParameterAsString(request, "content");

        User user = SecurityUtils.getCurrentUser(request);

        ResponseEntity rsp = new ResponseEntity();
        if (StringUtils.isBlank(fid) || StringUtils.isBlank(ftype)) {
            rsp.setSuccess(false);
            rsp.setMessage("fid、ftype未设置正确");
            return rsp;
        }
        if (StringUtils.isBlank(content)) {
            rsp.setSuccess(true);
            rsp.put("content", content);
            return rsp;
        }

        // 处理附件图片
        Document doc = Jsoup.parse(content);
        Elements images = doc.select("img");
        for (int i = 0; i < images.size(); i++) {
            Element image = images.get(i);
            String src = image.attr("src");
            try {
                URL url = new URL(src);
                Attachment attachment = attachmentService.createAttachment(user.getId(), url, ftype, fid);
                image.attr("src", UploadUtils.UPLOAD_FOLDER + attachment.getPath());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                continue;
            }
        }
        rsp.setSuccess(true);
        rsp.put("content", doc.html());
        return rsp;
    }
}
